<?php
namespace app\atxunda\model;
use think\Model;
use think\Input;
use think\Db;

class KnowUserNav extends Model
{
	public function setUserNav($userId,$param,$adminId){
		$nav_id = $param['nav_id'];
		$price = $param['price'];
		$classType = $param['classType'];
		// if($param['status'] == 7 || $param['status'] == 6) $classType = [];
		$spread = $param['spread'];
		$remarks = $param['remarks'];
		$study_num = $param['study_num'];
		$spread_id = $param['spread_id'];
		$sale_id = $param['sale_id'];
		$class_nav = $param['class_nav'];
		if($nav_id){
			$userNav = self::where(['user_id'=>$userId,'valid'=>'yes'])->column('nav_id');
			$delNavId = array_diff($userNav,$nav_id);
			if($delNavId) {
				self::where(['user_id'=>$userId,'nav_id'=>['in',implode(',', $delNavId)]])->delete();
				KnowUserSale::where(['user_id'=>$userId,'nav_id'=>['in',implode(',', $delNavId)]])->delete();
				Db::table('class_nav_user')->where(['user_id'=>$userId,'nav_id'=>['in',implode(',', $delNavId)]])->delete();
			}
			$arr = $saleArr = array();
			$year = 2+(count($nav_id)-1);
			if($param['year']) $year = $param['year'];
			$month = 0;
			if($nav_id)  foreach ($nav_id as $key => $nav) {
				if($classType[$key] == 'subscribe'){
					KnowUserSale::setUserSale($userId,$price[$key],$spread_id[$key],$sale_id[$key],$nav);
				}else{
					$typeIds = '';
					if($class_nav[$key]) {
						$study_num[$key] = '';
						$typeIds = Db::table('class_nav_type')->where('class_id','in',$class_nav[$key])->value('group_concat(type_id)');
						$navUser = Db::table('class_nav_user')->where(['user_id'=>$userId,'nav_id'=>$nav])->column('class_id');
						$delClassNavId = array_diff($navUser,$class_nav[$key]);
						if($delClassNavId) Db::table('class_nav_user')->where(['user_id'=>$userId,'nav_id'=>$nav,'class_id'=>['in',$delClassNavId]])->delete();
						$addClassNavId = array_diff($class_nav[$key],$navUser);
						if($addClassNavId) foreach($addClassNavId as $cn){
							Db::table('class_nav_user')->insert([
								'nav_id' => $nav,
								'user_id' => $userId,
								'class_id' => $cn,
								'created_admin_id' => $adminId,
								'updated_admin_id' => $adminId,
								'created_time' => time(),
								'updated_time' => time(),
							]);
						}
						$year = 0;
						$month = Db::table('nav_detail')->where('nav_id','in',$class_nav[$key])->where('course','yes')->order('month desc')->value('month') ?: 24;
					}else{
						Db::table('class_nav_user')->where(['user_id'=>$userId,'nav_id'=>$nav])->delete();
					}
					if(($price[$key] !== '' || $param['vip_id']) && !in_array($nav, $userNav)){
						$arr[$key]['nav_id'] = $saleArr[$key]['nav_id'] = $nav;
						$arr[$key]['user_id'] = $saleArr[$key]['user_id'] = $userId;
						$arr[$key]['orderid'] = 1;
						$arr[$key]['money'] = $saleArr[$key]['money'] = $price[$key] ? $price[$key] : 0;
						if($param['vip_id'] && !$classType[$key]) $classType[$key] = '视频班';
						$arr[$key]['classType'] = $classType[$key];
						$arr[$key]['time'] = $saleArr[$key]['time'] = date('Y-m-d H:i:s',time());
						$arr[$key]['spread'] = $spread[$key];
						$arr[$key]['remarks'] = $remarks[$key];
						$arr[$key]['study_num'] = $study_num[$key];
						$arr[$key]['type_id'] = $typeIds;
						$arr[$key]['spread_id'] = $saleArr[$key]['spread_id'] = $spread_id[$key];
						$arr[$key]['sale_id'] = $saleArr[$key]['sale_id'] = $sale_id[$key];
						$arr[$key]['is_see'] = 'no';
						$arr[$key]['vip_id'] = $param['vip_id'];
						$arr[$key]['expired_time'] = date('Y-m-d H:i:s',strtotime("+".$month." month +".$year." year"));
					}else{
						$user_nav = self::where(['nav_id'=>$nav,'user_id'=>$userId])->find();
						if($price[$key] != $user_nav['money'] || $classType[$key] != $user_nav['classType'] || $spread[$key] != $user_nav['spread'] || $remarks[$key] != $user_nav['remarks'] || $study_num[$key] != $user_nav['study_num'] || $sale_id[$key] != $user_nav['sale_id'] || $spread_id[$key] != $user_nav['spread_id'] || $typeIds != $user_nav['type_id']){
							$month = $year*12+$month;
							self::where(['nav_id'=>$nav,'user_id'=>$userId])->update([
								'money' => $price[$key],
								'classType' => $classType[$key],
								'spread' => $spread[$key],
								'remarks' => $remarks[$key],
								'study_num' => $study_num[$key],
								'spread_id' => $spread_id[$key],
								'sale_id' => $sale_id[$key],
								'type_id' => $typeIds,
								'vip_id' => $param['vip_id'],
								'expired_time' => ['exp','DATE_ADD(time, INTERVAL '.$month.' MONTH)'],
							]);
							KnowUserSale::setUserSale($userId,$price[$key],$spread_id[$key],$sale_id[$key],$nav);
						}
						if($price[$key] != $user_nav['money']) self::where(['nav_id'=>$nav,'user_id'=>$userId])->update(['time'=>date('Y-m-d H:i:s',time())]);
					}
				}
			}
			$navModel = new KnowUserNav;
			if($arr) $navModel->saveAll($arr);
			$saleModel = new KnowUserSale;
			if($saleArr) $saleModel->saveAll($saleArr);
		}else{
			self::where('user_id',$userId)->delete();
			KnowUserSale::where(['user_id'=>$userId])->delete();
		}
	}

	public function getUserNavIds($userId,$status = 'novip'){
		$vip_id = self::where(['user_id'=>$userId,'valid'=>'yes'])->value('vip_id');
		if($status == 'vip'){
			$userVip = Db::table('know_user_vip')->where('id',$vip_id)->find();
			if($userVip['type'] != 3 && $userVip['type'] != 4) return [];
		}
		return self::where(['user_id'=>$userId,'valid'=>'yes'])->column('nav_id');
	}

	public function getUserNavClass($userId,$ids){
		$nav_data = Db::table('nav')->where('is_show',1)->order('nav_sort desc')->select();
		$class = Db::table('class_nav_type')
					->field('class_nav.id,title,type_id,nav_id')
					->join('class_nav','class_id=class_nav.id')
					->where('nav_id','in',array_column($nav_data, 'nav_id'))
					->order('class_id asc')->select();
		$classData = [];
		if($class) foreach ($class as $key => $vc) {
			$typeDatas = Db::table('type')->where('type_id','in',$vc['type_id'])->order('type_sort desc')->column('type_name');
			foreach ($typeDatas as $kt => $vt) {
				$begin = substr($vt, 0,strpos($vt, '：')+3);
				$end = str_replace($vt, trim($begin), returnNum(trim($begin)));
				if($end !== false) $typeDatas[$kt] = $end;
			}
			$vc['study_num'] = returnContinuity(implode(',', $typeDatas));
			$classData[$vc['nav_id']][] = $vc;
		}
		foreach ($nav_data as $key => $v) {
			$user_nav = self::field('money,classType,study_num,spread,remarks,sale_id,spread_id')
						->where(['user_id'=>$userId,'nav_id'=>$v['nav_id'],'valid'=>'yes'])
						->find();
			if(!$user_nav) {
				$user_sale = Db::table('know_user_sale')->where(['user_id'=>$userId,'nav_id'=>$v['nav_id']])->where('sale_id != 0 or spread_id !=0')->order('time desc')->select();
				if($user_sale){
					$user_nav['money'] = array_sum(array_column($user_sale, 'money'));
					$user_nav['classType'] = 'subscribe';
					$user_nav['spread_id'] = $user_sale[0]['spread_id'];
					$user_nav['sale_id'] = $user_sale[0]['sale_id'];
					$ids[] = $v['nav_id'];
					$nav_data[$key]['branch_sale'] = $user_sale[0]['sale_id'];
					$nav_data[$key]['branch_spread'] = $user_sale[0]['spread_id'];
					$nav_data[$key]['branch_spread_user'] = BranchUser::getUserIds($user_sale[0]['spread_id']);
					$nav_data[$key]['branch_sale_user'] = BranchUser::getUserIds($user_sale[0]['sale_id']);
				}
			}
			$package = Db::table('package_nav')->field('name,price')
						->join('package','package_id=package.id')
						->where('nav_id',$v['nav_id'])->order('name asc')->select();
			$nav_data[$key]['user_nav'] = $user_nav;
			$nav_data[$key]['package'] = $package;
			$nav_data[$key]['classNav'] = $classData[$v['nav_id']];
			$nav_data[$key]['inputDis'] = 'input_new';
			$sale_id = BranchUser::getUserBranchId($user_nav['sale_id']);
			$spread_id = BranchUser::getUserBranchId($user_nav['spread_id']);
			$nav_data[$key]['branch_sale'] = $sale_id;
			$nav_data[$key]['branch_spread'] = $spread_id;
			$nav_data[$key]['branch_spread_user'] = BranchUser::getUserIds($spread_id);
			$nav_data[$key]['branch_sale_user'] = BranchUser::getUserIds($sale_id);
			if(in_array($v['nav_id'], $ids)) $nav_data[$key]['inputDis'] = 'input_edit';
		}
		return ['nav_data'=>$nav_data,'ids'=>$ids];
	}
}